# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
from collections import defaultdict
from cerbero.utils import shell
from custom import list_gstreamer_1_0_plugins_by_category

DECLARE_PLUGIN_TPL = 'GST_PLUGIN_STATIC_DECLARE(%s);'
REGISTER_PLUGIN_TPL = '    GST_PLUGIN_STATIC_REGISTER(%s);'
DEFINE_TPL = '#define GST_IOS_PLUGINS_%s\n'
DEFINES_TPL = '''\
#if defined(GST_IOS_PLUGIN_%s) || defined(GST_IOS_PLUGINS_%s)
%s
#endif'''

class Recipe(recipe.Recipe):
    name = 'gstreamer-ios-templates'
    version = '0.1'
    licenses = [License.LGPLv2_1Plus]
    stype = SourceType.CUSTOM
    btype = BuildType.CUSTOM
    deps = ['gstreamer-1.0', 'gst-plugins-base-1.0', 'gst-plugins-good-1.0',
        'gst-plugins-ugly-1.0', 'gst-plugins-bad-1.0', 'gst-libav-1.0',
        'gst-devtools-1.0', 'gst-rtsp-server-1.0', 'gst-editing-services-1.0'
    ]

    files_devel = [
            'share/xcode/templates/ios/',
            ]

    async def install(self):
        share_dir = os.path.join(self.config.prefix, 'share', 'xcode',
                                 'templates', 'ios')
        shell.copy_dir(os.path.join(self.config.data_dir, 'xcode',
                                    'templates', 'ios'), share_dir)

        plugins = list_gstreamer_1_0_plugins_by_category(self.config)

        decls = []
        regs = []
        categories = ''
        for c, ps in plugins.items():
            c = c.upper()
            define = DEFINE_TPL % c
            # By default enable only the core plugins
            if c != 'CORE':
              define = '//%s' % define
            categories += define
            for p in ps:
                p_up = p.upper()
                decls.append(DEFINES_TPL % (p_up, c, DECLARE_PLUGIN_TPL % p))
                regs.append(DEFINES_TPL % (p_up, c, REGISTER_PLUGIN_TPL % p))
        tpl_dir = os.path.join(share_dir, 'GStreamer Base.xctemplate')
        iosinit_m = os.path.join(tpl_dir, 'gst_ios_init.m')
        iosinit_h = os.path.join(tpl_dir, 'gst_ios_init.h')
        shell.replace (iosinit_h, {'@GST_IOS_PLUGINS_CATEGORIES@': categories})
        shell.replace (iosinit_m, {
            '@GST_IOS_PLUGINS_DECLARE@': '\n'.join(decls),
            '@GST_IOS_PLUGINS_REGISTER@': '\n'.join(regs)})
